<template>
  <div class="app-container">
    <div class="page-header">
      <el-button
        type="text"
        @click="goBack"
        class="back-btn"
        style="background-color: #fff; padding: 8px 6px; border-radius: 4px; border: 1px solid #e6e6e6; width: 80px;"
      >
        <img
          src="@/assets/images/icon_back.png"
          alt="返回"
          style="width: 12px; vertical-align: middle; margin-right: 8px;"
        >
        <span style="color: #0C1124;">返回</span>
      </el-button>
      <div class="title-bar">
        <span class="page-title">项目名称：{{projectForm.whitePaperName}}  ； 企业名称：{{projectForm.orgName}}  ； 所在行业：{{projectForm.industry}}</span>
      </div>
    </div>

    <div class="content-layout">
      <div class="layout-left">
        <div class="panel">
          <div class="panel-header">白皮书大纲</div>
          <div class="outline-list">
            <div v-if="!chapters || chapters.length === 0" class="empty-tip" style="line-height: 200px;">
              暂无大纲数据
            </div>
            <div
              class="chapter-item"
              v-for="(chapter, idx) in chapters"
              :key="idx"
              :class="{
                expanded: chapter.isExpanded,
                'last-chapter': idx === chapters.length - 1
              }"
            >
              <div class="chapter-header" @click="toggleChapter(idx)">
                <div class="chapter-header-left">
                  <img src="@/assets/images/icon_outline.png" alt="大纲图标" class="outline-icon">
                  <span>{{ chapter.chapterName || '未命名章节' }}</span>
                </div>
                <i class="el-icon" :class="chapter.isExpanded ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i>
              </div>
              <div class="chapter-children" v-if="chapter.isExpanded">
                <div v-if="!chapter.contentTitles || chapter.contentTitles.length === 0" style="color: #999; padding: 8px 0;">
                  暂无内容标题
                </div>

                <div class="title-wrapper" v-for="(titleItem, cIdx) in chapter.contentTitles" :key="cIdx">
                  <div class="title-item" @click="showChapterDetail(titleItem)">
                    <span>{{ titleItem.title || '未命名标题' }}</span>
                  </div>
                  <div class="title-info-area">
                    <div class="sub-title-list">
                      <div class="sub-title-item" v-for="(subTitle, sIdx) in titleItem.subTitles" :key="sIdx" @click="showChapterDetail({...titleItem, ...subTitle})">
                        {{ subTitle.label || '暂无' }}
                      </div>
                    </div>
                    <div class="meta-content">
                      <span class="meta-item">{{ titleItem.dataSource || '暂无' }}</span>
                      <span class="meta-item">时间：{{ formatDate(titleItem.createTime) || '暂无' }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="layout-middle">
        <div class="panel">
          <div class="panel-header">调研分析</div>
          <div class="middle-content">
            <div class="research-content" v-if="currentDetail.aiAnalyseResult">
              <div v-html="currentDetail.aiAnalyseResult"></div>
            </div>
            <div class="empty-tip" v-else>
              请点击左侧大纲标题查看调研分析
            </div>
          </div>
        </div>
      </div>

      <div class="layout-right">
        <div class="panel">
          <div class="panel-header content-assembly-header">
            <span>内容汇编</span>
          </div>
          <div class="editor-wrapper">
            <Editor
              v-model="editorContent"
              class="full-height-editor"
              :options="editorOptions"
              :disabled="!currentDetail.id"
            ></Editor>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Editor from '@/components/Editor/index.vue'
import { getToken } from "@/utils/auth";
import axios from "axios";
import { projectTree,getProject,detailList } from "@/api/whitepaper/project"

export default {
  components: { Editor },
  data() {
    return {
      projectForm:{},
      paperName: '',
      defaultPaperName: '',
      projectId: 0,
      chapters: [],
      currentDetail: {},
      editorContent: '',
      editorOptions: {
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            ['blockquote', 'code-block'],
            [{ 'header': 1 }, { 'header': 2 }],
            [{ 'list': 'ordered'}, { 'list': 'bullet' }],
            [{ 'align': [] }],
            ['link', 'image'],
            ['clean']
          ]
        },
        theme: 'snow',
        scrollingContainer: null
      },
      headers: { Authorization: "Bearer " + getToken() },
      listData: []
    };
  },
  mounted() {
    this.projectId = this.$route.query.id
    if (!this.projectId) {
      this.$message.error("未获取到有效项目ID");
      return;
    }

    this.getInfo(this.projectId)

    Promise.all([
      this.getOutlineDetailList(),
      this.getOutlineList()
    ])
    .then(() => {
      this.mergeData();
    })
    .catch(() => this.$message.error("数据加载失败，请刷新重试"));

    this.hideSidebar()
    this.adjustMainContent()
    document.body.style.overflow = 'hidden'
    document.documentElement.style.overflow = 'hidden'
    this.extendContentLayout()
  },
  beforeDestroy() {
    this.restoreSidebar()
    this.restoreMainContent()
    document.body.style.overflow = ''
    document.documentElement.style.overflow = ''
  },
  methods: {
    getInfo(id) {
      getProject(id).then(res => {
        this.projectForm = res.data
      })
    },
    parseProjectIdFromUrl() {
      try {
        const pathSegments = window.location.pathname.split('/').filter(seg => seg);
        const lastSegment = pathSegments[pathSegments.length - 1];
        const pathId = Number(lastSegment);
        if (Number.isInteger(pathId) && pathId > 0) return pathId;

        const urlParams = new URLSearchParams(window.location.search);
        const queryId = Number(urlParams.get('id'));
        return Number.isInteger(queryId) && queryId > 0 ? queryId : 0;
      } catch (err) {
        return 0;
      }
    },

    async getWhitepaperDetail() {
      try {
        const res = await axios.get(
          `${process.env.VUE_APP_BASE_API}/system/project/${this.projectId}`,
          { headers: this.headers }
        );
        const { code, data } = res.data || {};
        if (code === 200 && data) {
          this.paperName = data.paperName || data.whitePaperName || data.name || '';
          if (!this.paperName) this.$message.warning("获取到白皮书数据，但未找到名称字段");
        } else {
          this.paperName = this.defaultPaperName || '未命名白皮书';
        }
      } catch (err) {
        this.paperName = this.defaultPaperName || '未命名白皮书';
      }
    },

    async getOutlineDetailList() {
      try {
        const res = await axios.get(
          `${process.env.VUE_APP_BASE_API}/system/project/detailList`,
          { params: { id: this.projectId }, headers: this.headers }
        );
        const { code, data } = res.data || {};
        if (code !== 200) throw new Error();
        if (!data || !data.length) {
          this.$message.warning("暂无大纲数据");
          this.chapters = [{ chapterName: '默认章节', contentTitles: [], isExpanded: true }];
          return;
        }

        this.chapters = data.map(chapter => {
          const contentTitles = (chapter.outlineList || []).map(item => ({
            ...item,
            subTitles: []
          }));
          if (!this.defaultPaperName) this.defaultPaperName = chapter.chapterName || '未命名白皮书';
          return {
            chapterName: chapter.chapterName || '未命名章节',
            contentTitles: contentTitles,
            isExpanded: true
          };
        });
      } catch (err) {
        this.$message.error("大纲加载失败");
        this.chapters = [{ chapterName: '默认章节', contentTitles: [{ title: '暂无内容标题' }], isExpanded: true }];
      }
    },

    async getOutlineList() {
      try {
        const res = await axios.get(
          `${process.env.VUE_APP_BASE_API}/system/project/tree`,
          { params: { id: this.projectId }, headers: this.headers }
        );
        const { code, data } = res.data || {};
        if (code === 200 && Array.isArray(data)) {
          this.listData = data;
        } else {
          this.listData = [];
        }
      } catch (err) {
        this.listData = [];
        console.error(err);
      }
    },

    mergeData() {
      if (!this.chapters.length || !this.listData.length) return;

      this.chapters = this.chapters.map(chapter => {
        const matchListChapter = this.listData.find(l => l.label === chapter.chapterName);
        const contentTitles = chapter.contentTitles.map(titleItem => {
          const matchListTitle = matchListChapter?.children?.find(l => l.id === titleItem.id);
          const subTitles = matchListTitle?.children || [];

          return {
            ...titleItem,
            dataSource: matchListTitle?.children[0]?.summary || titleItem.dataSource,
            aiAnalyseResult: matchListTitle?.children[0]?.content || titleItem.aiAnalyseResult,
            subTitles: subTitles
          };
        });

        return {
          ...chapter,
          contentTitles: contentTitles
        };
      });

      const firstChapter = this.chapters[0];
      const firstTitle = firstChapter?.contentTitles[0];
      if (firstTitle) {
        this.showChapterDetail(firstTitle);
      }
    },

    showChapterDetail(titleItem) {
      this.currentDetail = titleItem;
      this.editorContent = titleItem.fianlAnalyseResult || '';
    },

    formatDate(timeStr) {
      if (!timeStr) return '';
      return timeStr.slice(0, 10);
    },

    toggleChapter(idx) {
      this.chapters[idx].isExpanded = !this.chapters[idx].isExpanded;
    },
    goBack() {
      this.$router.push({ path: '/index'})
    },
    manageTask() {
       window.location.href = `/whitepaper/form?projectId=${this.projectId}&step=3`;
    },
    hideSidebar() {
      const selectors = ['.sidebar', '.sidebar-container', '.el-layout__sider', '.sidebar-wrap'];
      selectors.forEach(sel => {
        const el = document.querySelector(sel);
        if (el) Object.assign(el.style, { visibility: 'hidden', width: '0px !important', height: '0px !important', padding: '0 !important', margin: '0 !important', overflow: 'hidden !important' });
      });
    },
    restoreSidebar() {
      const selectors = ['.sidebar', '.sidebar-container', '.el-layout__sider', '.sidebar-wrap'];
      selectors.forEach(sel => {
        const el = document.querySelector(sel);
        if (el) Object.assign(el.style, { visibility: '', width: '', height: '', padding: '', margin: '', overflow: '' });
      });
    },
    restoreMainContent() {
      const appMain = document.querySelector('.app-main');
      const mainContainer = document.querySelector('.main-container');
      const layoutContent = document.querySelector('.el-layout__content');
      if (appMain) Object.assign(appMain.style, { marginLeft: '', width: '', padding: '' });
      if (mainContainer) Object.assign(mainContainer.style, { width: '', overflow: '', height: '' });
      if (layoutContent) Object.assign(layoutContent.style, { marginLeft: '', width: '' });
    },
    adjustMainContent() {
      const appMain = document.querySelector('.app-main');
      const mainContainer = document.querySelector('.main-container');
      const layoutContent = document.querySelector('.el-layout__content');
      if (appMain) Object.assign(appMain.style, { marginLeft: '0px !important', width: '100% !important', padding: '0 !important' });
      if (mainContainer) Object.assign(mainContainer.style, { width: '100% !important', overflow: 'hidden !important', height: '98vh !important' });
      if (layoutContent) Object.assign(layoutContent.style, { marginLeft: '0px !important', width: '100% !important' });
    },
    extendContentLayout() {
      const contentLayout = document.querySelector('.content-layout');
      if (contentLayout) {
        contentLayout.style.height = 'calc(98vh - 80px - 10px)';
        contentLayout.style.transition = 'height 1s ease-in-out';
      }
    },
    async handleSaveEditor() {
      try {
        const submitData = {
          id: this.currentDetail.id,
          fianlAnalyseResult: this.editorContent,
          projectId: this.projectId,
          delFlag: this.currentDetail.delFlag || '0'
        };

        const res = await updateOutline(submitData);
        const { code, msg } = res.data || {};

        if (code === 200) {
          this.$message.success('保存成功！');
          this.currentDetail.fianlAnalyseResult = this.editorContent;
        } else {
          throw new Error(msg || '保存失败');
        }
      } catch (err) {
        this.$message.error(`保存失败：${err.message || '网络异常'}`);
        console.error('保存修改出错：', err);
      }
    }
  }
};
</script>

<style scoped>
html, body, .app-container {
  height: 98vh !important;
  margin: 0;
  background-color: #EBEFF2;
}
.app-container {
  padding: 40px 20px 10px;
  box-sizing: border-box;
  width: 100% !important;
}

.page-header {
  height: 80px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  margin-bottom: 10px;
  width: 100%;
}
.back-btn {
  margin-bottom: 10px;
}
.title-bar {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.page-title {
  font-size: 20px;
  font-weight: 600;
}

.content-layout {
  display: flex;
  gap: 10px;
  height: calc(98vh - 80px - 10px);
  transition: height 1s ease-in-out;
  width: 100% !important;
  overflow: hidden;
}

.layout-left, .layout-middle, .layout-right {
  height: 100%;
  flex-shrink: 0;
  width: 500px;
}
.layout-middle {
  width: 860px;
  min-width: 300px;
}
.layout-right {
  width: 500px;
}

.panel {
  width: 100% !important;
  height: 100%;
  background: #fff;
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  position: relative;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}
.panel-header {
  padding: 15px;
  padding-left: 19px;
  font-size: 18px;
  font-weight: 600;
  border-bottom: 1px solid #e6e6e6;
  flex-shrink: 0;
  height: 58px;
  box-sizing: border-box;
}

/* 内容汇编标题栏样式 */
.content-assembly-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-right: 15px;
}
.save-edit-btn {
  padding: 6px 12px !important;
  font-size: 14px !important;
}


.outline-list {
  padding: 10px 15px;
  font-size: 14px;
  overflow-y: auto !important;
  font-weight: bold;
  flex: 1;
  max-height: calc(100% - 100px);
  box-sizing: border-box;
}

.chapter-item {
  position: relative;
  margin-bottom: 8px;
  padding-left: 5px;
  font-size: 16px;
  font-weight: bold;
}
.chapter-item::before {
  content: '';
  position: absolute;
  left: 11px;
  top: 27px;
  bottom: 0;
  width: 1px;
  background-color: #D8DFEB;
  display: none;
}
.chapter-item.expanded::before {
  display: block;
}
.chapter-item.last-chapter::before {
  display: none !important;
}
.chapter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
}
.chapter-header-left {
  display: flex;
  align-items: center;
  gap: 8px;
}
.outline-icon {
  width: 14px;
  height: 14px;
  vertical-align: middle;
}
.chapter-children {
  margin-left: 12px;
  padding-left: 8px;
  position: relative;
}

.title-wrapper {
  margin: 12px 0;
  padding-left: 10px;
}
.title-item {
  color: #0C1124;
  cursor: pointer;
  transition: color 0.2s;
  font-weight: 600;
  font-size: 14px;
}
.title-item:hover {
  color: #165dff;
}
.title-info-area {
  background-color: #EEF4FA;
  border-radius: 2px;
  padding: 10px 12px;
  margin: 6px 0;
}
.meta-content {
  font-size: 12px;
  color: #606C80;
  line-height: 1.5;
  margin-top: 8px;
  display: flex;
  align-items: center;
}
.meta-item {
  margin: 0;
  margin-right: 20px;
}
.meta-item:last-child {
  margin-right: 0;
}
.sub-title-list {
  margin-left: 0;
  padding-left: 0;
  border-left: none;
}
.sub-title-item {
  font-size: 14px;
  color: #0C1124;
  margin: 4px 0;
  cursor: pointer;
  transition: color 0.2s;
}
.sub-title-item:hover {
  color: #165dff;
}


.middle-content {
  flex: 1;
  overflow-y: auto !important;
  padding: 0 25px;
  box-sizing: border-box;
  max-height: calc(100% - 110px);
}
.research-content {
  font-size: 15px;
  line-height: 1.7;
  padding: 10px 0;
}
.empty-tip {
  padding: 25px;
  font-size: 14px;
  color: #999;
  text-align: center;
  line-height: 300px;
  min-height: 100%;
}

.editor-wrapper {
  flex: 1;
  overflow: hidden;
  max-height: calc(100% - 100px);
}
.full-height-editor {
  height: 100% !important;
  border: none !important;
}

::v-deep .ql-container {
  height: calc(100% - 55px) !important;
  overflow-y: auto !important;
  border: none !important;
  box-shadow: none !important;
}
::v-deep .ql-editor {
  min-height: 100% !important;
  border: none !important;
  padding: 15px !important;
}
::v-deep .ql-toolbar {
  border: none !important;
  border-bottom: 1px solid #e6e6e6 !important;
  box-shadow: none !important;
  height: 55px !important;
  box-sizing: border-box;
}


::v-deep .outline-list::-webkit-scrollbar,
::v-deep .middle-content::-webkit-scrollbar,
::v-deep .ql-editor::-webkit-scrollbar {
  width: 6px;
}
::v-deep .outline-list::-webkit-scrollbar-thumb,
::v-deep .middle-content::-webkit-scrollbar-thumb,
::v-deep .ql-editor::-webkit-scrollbar-thumb {
  border-radius: 3px;
  background-color: #ccc;
}
</style>

<style>
.sidebar,
.sidebar-container,
.el-layout__sider,
.sidebar-wrap {
  visibility: hidden !important;
  width: 0px !important;
  height: 0px !important;
  padding: 0 !important;
  margin: 0 !important;
  overflow: hidden !important;
}

.main-container {
  width: 100% !important;
  margin: 0 !important;
  padding: 0 !important;
  overflow: hidden !important;
  height: 98vh !important;
}

.app-main {
  margin-left: 0px !important;
  width: 100% !important;
  overflow: hidden !important;
  height: 98vh !important;
}
</style>
